﻿#include "readersql.h"
#include <QMessageBox>
#include <QCoreApplication>
#include <QSqlQuery>
#include <QtDebug>
#include <QSqlError>
#include <QDir>
Readersql::Readersql(QObject *parent)
    : QObject{parent}
{ init();
    //q.exec("INSERT INTO Reader VALUES(16,'MC[]aa2397','bear',19,2,'st',2131,'110','1@qq.com')");
}

void Readersql::init()
{    if(QSqlDatabase::drivers().isEmpty())
        QMessageBox::information(nullptr,tr("No database drvers found"),tr("This demo requires at least one Qt database driver."
                                                                      "Please check the documentation how to build the "
                                                                      "Qt SQL plugins."));
   qDebug()<<"reader initializing begin";
   m_db = QSqlDatabase::addDatabase("QSQLITE");
   m_db.setDatabaseName("C:\\LIBDB\\data.db");
   if(!m_db.open())
        QMessageBox::warning(nullptr,tr("Unable to open database"),tr("An error occurred while "));
    qDebug()<<"reader initializing end";


}

bool Readersql::addStu(ReaderInfo info)
{

    QSqlQuery sql(m_db);
    QString strSql = QString("INSERT INTO Reader values('%1','%2','%3',%4,%5,'%6',%7,'%8','%9',0,'%10','%11')").
                     arg(info.ID).
                     arg(info.password).
                     arg(info.name).
                     arg(info.age).
                     arg(info.grade).
                     arg(info.major).
                     arg(info.studentid).
                     arg(info.phone).
                     arg(info.email).
                     arg(info.book_borrowed).
                     arg(info.book_overtime);

    qDebug()<<"add_user function working "<<strSql;
    sql.exec(strSql);
    //sql.exec("INSERT INTO Reader (id, name, salary) "           "VALUES (1001, 'Thad Beaumont', 65000)");
    return true;
}

QString Readersql::Password(QString user)
{

 QSqlQuery sql(m_db);

 QString strSql = QString("SELECT * FROM Reader WHERE ID=%1").arg(user);
 sql.exec(strSql);
 if(sql.next())
 {qDebug()<<"Found";}
 return sql.value(1).toString();
}

int Readersql::fn(QChar c)
{if(c==QChar('0')) return 0;
    if(c==QChar('1')) return 1;
    if(c==QChar('2')) return 2;
    if(c==QChar('3')) return 3;
    if(c==QChar('4')) return 4;
    if(c==QChar('5')) return 5;
    if(c==QChar('6')) return 6;
    if(c==QChar('7')) return 7;
    if(c==QChar('8')) return 8;
    if(c==QChar('9')) return 9;
    return -1;

}

int Readersql::char_to_int(QString s)
{int ret=0;
    for(int i=0;i<s.length();i++)
      { if(fn(s[i])==-1)
        {qDebug()<<"请输入正确的数字！";
         return -1;
        }
        ret = 10*ret + fn(s[i]);

      }
    return ret;

}
